//
//  COHomeListViewController.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/19.
//

import UIKit
import CollectionViewWaterfallLayout
import JXSegmentedView
import MJRefresh

class COHomeListViewController: COBaseViewController {
    private var page = 1
    private var contents: [COHomeListModel] = []
    
    private let isMy: Bool
    private let heId: Int
    
    init(_ isMy: Bool = false, heId: Int = 0) {
        self.isMy = isMy
        self.heId = heId
        super.init(nibName: nil, bundle: nil)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override var navShow: Bool {
        if isMy {
            return true
        }
        return false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.collectionView.mj_header?.beginRefreshing()
    }
    
    
    override func configUI() {
        view.backgroundColor = .rgba(17, 7, 41, 1)
        view.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            if self.isMy {
                make.top.equalToSuperview().offset(statusBarHeight + navHeight)
            } else {
                make.top.equalToSuperview()
            }
        }
    }
    

    private lazy var collectionView: UICollectionView = {
        let layout = CollectionViewWaterfallLayout()
        layout.columnCount = 2
        layout.minimumColumnSpacing = 15
        layout.minimumInteritemSpacing = 10
    
        layout.sectionInset = .init(top: 27, left: 7, bottom: 0, right: 7)
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .rgba(17, 7, 41, 1)
        cv.delegate = self
        cv.dataSource = self
        cv.register(COHomeListCollectionViewCell.self, forCellWithReuseIdentifier: COHomeListCollectionViewCell.identifier)
        
        cv.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.page = 1
            self?.getData()
        })
        
        cv.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.page += 1
            self?.getData()
        })
        return cv
    }()

}

extension COHomeListViewController: CollectionViewWaterfallLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return contents[indexPath.row].cellSize
    }
    
    
}

extension COHomeListViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        contents.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: COHomeListCollectionViewCell.identifier, for: indexPath) as! COHomeListCollectionViewCell
        cell.model = contents[indexPath.row]
        return cell
    }
    
    private func getData() {
        if isMy {
            getMyData()
            return
        }
        
        if heId > 0 {
            geHeData()
            return
        }
        CONetwork.sendRequest(provider: homeProvider, target: .square(page: page)) { text in
            guard let array = text.array else {
                return
            }
            
            let arr = array.map({ dic in
                let model = COHomeListModel.deserialize(from: dic)!
                model.cellChange = {[weak self] in
                    self?.collectionView.reloadData()
                }
                return model
            })
            if self.page == 1 {
                self.contents = arr
                self.collectionView.mj_header?.endRefreshing()
            } else {
                self.contents.append(contentsOf: arr)
            }
            
            if arr.count < 20 {
                self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.collectionView.mj_footer?.endRefreshing()
            }
            
            self.collectionView.reloadData()
        } failedBlock: { _, text in
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            self.view.makeToast(text, position: .center)
        }

    }
    
    
    private func getMyData() {
        CONetwork.sendRequest(provider: mineProvider, target: .sqList(page: page)) { text in
            guard let array = text.array else {
                return
            }
            
            let arr = array.map({ dic in
                let model = COHomeListModel.deserialize(from: dic)!
                model.cellChange = {[weak self] in
                    self?.collectionView.reloadData()
                }
                return model
            })
            if self.page == 1 {
                self.contents = arr
                self.collectionView.mj_header?.endRefreshing()
            } else {
                self.contents.append(contentsOf: arr)
            }
            
            if arr.count < 20 {
                self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.collectionView.mj_footer?.endRefreshing()
            }
            
            self.collectionView.reloadData()
        } failedBlock: { _, text in
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            self.view.makeToast(text, position: .center)
        }

    }
    
    private func geHeData() {
        CONetwork.sendRequest(provider: heProvider, target: .sq(id: heId, page: page)) { text in
            guard let array = text.array else {
                return
            }
            
            let arr = array.map({ dic in
                let model = COHomeListModel.deserialize(from: dic)!
                model.cellChange = {[weak self] in
                    self?.collectionView.reloadData()
                }
                return model
            })
            if self.page == 1 {
                self.contents = arr
                self.collectionView.mj_header?.endRefreshing()
            } else {
                self.contents.append(contentsOf: arr)
            }
            
            if arr.count < 20 {
                self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.collectionView.mj_footer?.endRefreshing()
            }
            
            self.collectionView.reloadData()
        } failedBlock: { _, text in
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            self.view.makeToast(text, position: .center)
        }

    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = COSquareDetailViewController()
        vc.model = contents[indexPath.row]
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension COHomeListViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}



extension UICollectionViewCell {
    static var identifier: String {
        return String(describing: Self.self)
    }
}

